<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :width="state.dialog.dialogWidth">
			<el-form ref="menuDialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="80px">
				<el-row :gutter="35">
					<template v-if="state.dialog.type == 4 || state.dialog.type == 5">
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="按钮名称" required>
								<el-input v-model="state.btnName" placeholder="请输入按钮名称" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="按钮标识" required>
								<el-input v-model="state.btnCode" placeholder="请输入按钮唯一标识如menu.btn" clearable></el-input>
							</el-form-item>
						</el-col>
					</template>
					<template v-else>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单名称" prop="title">
								<el-input v-model="state.ruleForm.title" placeholder="请输入菜单名称" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由名称" prop="name">
								<el-input v-model="state.ruleForm.name" placeholder="路由中的 name 值" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="路由路径" prop="path">
								<el-input v-model="state.ruleForm.path" placeholder="路由中的 path 值" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="state.dialog.type == 1 || state.dialog.type == 3" class="mb20">
							<el-form-item label="重定向">
								<el-input v-model="state.ruleForm.redirect" placeholder="请输入路由重定向" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="标识" prop="code">
								<el-input v-model="state.ruleForm.code" placeholder="唯一标识例如:admin" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单图标">
								<IconSelector placeholder="请输入菜单图标" v-model="state.ruleForm.icon" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="组件路径" prop="component">
								<el-input v-model="state.ruleForm.component" placeholder="请输入组件路径" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="菜单排序">
								<el-input-number v-model="state.ruleForm.sortNo" controls-position="right" placeholder="请输入排序" class="w100" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="是否隐藏">
								<el-radio-group v-model="state.ruleForm.isHide">
									<el-radio :label="true">隐藏</el-radio>
									<el-radio :label="false">不隐藏</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="页面缓存">
								<el-radio-group v-model="state.ruleForm.isKeepAlive">
									<el-radio :label="true">缓存</el-radio>
									<el-radio :label="false">不缓存</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="嵌套">
								<el-radio-group v-model="state.ruleForm.isContentPage">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(menuDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '/@/stores/routesList';
import { i18n } from '/@/i18n/index';
import { FormInstance, ElMessage, dialogEmits } from 'element-plus';
// import { setBackEndControlRefreshRoutes } from "/@/router/backEnd";
import { MenuCreateMenu, MenuUpdate, CreateButton, UpdateButton } from '/@/api/menu/index';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 引入组件
const IconSelector = defineAsyncComponent(() => import('/@/components/iconSelector/index.vue'));

// 定义变量内容
const menuDialogFormRef = ref<FormInstance>();
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
const state = reactive({
	// 参数请参考 `/src/router/route.ts` 中的 `dynamicRoutes` 路由菜单格式
	ruleForm: {
		// menuSuperior: [], // 上级菜单
		// menuType: 'menu', // 菜单类型
		name: '', // 路由名称
		component: '', // 组件路径
		// componentAlias: '', // 组件路径别名
		isLink: false, // 是否外链
		sortNo: 0, // 菜单排序
		path: '', // 路由路径
		code: '', // 唯一标识
		moduleType: 1,
		redirect: '', // 路由重定向，有子集 children 时
		// meta: {
		// 	title: '', // 菜单名称
		// 	icon: '', // 菜单图标
		// 	isHide: false, // 是否隐藏
		// 	isKeepAlive: true, // 是否缓存
		// 	isAffix: false, // 是否固定
		// 	isLink: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
		// 	isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
		// 	roles: '', // 权限标识，取角色管理
		// },
		title: '', // 菜单名称
		icon: '', // 菜单图标
		isHide: false, // 是否隐藏
		isKeepAlive: false, // 是否缓存
		// isAffix: false, // 是否固定+
		// isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
		// roles: '', // 权限标识，取角色管理
		// btnPower: '', // 菜单类型为按钮时，权限标识
	} as any,
	menuData: [] as RouteItems, // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '' as any,
		title: '',
		submitTxt: '',
		dialogWidth: '800px',
		row: {} as any,
	},
	btnName: '', // 按钮名称
	btnCode: '', // 按钮标识
});
const rules = reactive({
	title: [{ required: true, message: '请输入预警名称', trigger: ['blur', 'change'] }],
	name: [{ required: true, message: '请输入路由名称', trigger: ['blur', 'change'] }],
	path: [{ required: true, message: '请输入路由路径', trigger: ['blur', 'change'] }],
	redirect: [{ required: true, message: '请输入路由重定向', trigger: ['blur', 'change'] }],
	code: [{ required: true, message: '请输入唯一标识', trigger: ['blur', 'change'] }],
	component: [{ required: true, message: '请输入组件路径', trigger: ['blur', 'change'] }],
});
// 获取 pinia 中的路由
const getMenuData = (routes: RouteItems) => {
	const arr: RouteItems = [];
	routes.map((val: RouteItem) => {
		val['title'] = i18n.global.t(val.meta?.title as string);
		arr.push({ ...val });
		if (val.children) getMenuData(val.children);
	});
	return arr;
};
// 打开弹窗
const openDialog = (type: any, row?: any) => {
	menuDialogFormRef.value?.resetFields();
	state.ruleForm = initializeForm();
	state.dialog.row = {};
	state.btnCode = '';
	state.btnName = '';
	state.dialog.dialogWidth = '800px';
	if (type == 1) {
		state.dialog.title = '新增菜单';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
	} else if (type == 2) {
		state.dialog.row = row;
		state.dialog.title = `新增 ${row.title} 子菜单`;
		state.dialog.submitTxt = '修 改';
		state.dialog.type = type;
	} else if (type == 4) {
		state.dialog.row = row;
		state.dialog.dialogWidth = '500px';
		state.dialog.title = `新增${row.title}按钮`;
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;
	} else if (type == 5) {
		state.dialog.row = row;
		state.dialog.dialogWidth = '500px';
		state.dialog.title = `修改按钮`;
		state.dialog.submitTxt = '修 改';
		state.dialog.type = type;
		state.btnCode = row.code;
		state.btnName = row.name;
	}
	if (row && type == 3) {
		state.dialog.row = row;
		for (const key in state.ruleForm) {
			if (row[key]) state.ruleForm[key] = row[key];
		}
		state.dialog.title = `修改子菜单`;
		state.dialog.submitTxt = '修 改';
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 是否内嵌下拉改变
const initializeForm = () => ({
	// menuSuperior: [], // 上级菜单
	// menuType: 'menu', // 菜单类型
	name: '', // 路由名称
	component: '', // 组件路径
	// componentAlias: '', // 组件路径别名
	isLink: false, // 是否外链
	sortNo: 0, // 菜单排序
	path: '', // 路由路径
	redirect: '', // 路由重定向，有子集 children 时
	moduleType: 1,
	code: '', // 唯一标识
	// meta: {
	// 	title: '', // 菜单名称
	// 	icon: '', // 菜单图标
	// 	isHide: false, // 是否隐藏
	// 	isKeepAlive: true, // 是否缓存
	// 	isAffix: false, // 是否固定
	// 	isLink: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，`1、isLink: 链接地址不为空`
	// 	isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
	// 	roles: '', // 权限标识，取角色管理
	// },
	title: '', // 菜单名称
	icon: '', // 菜单图标
	isHide: false, // 是否隐藏
	isContentPage: false, // 是否嵌套
	isKeepAlive: false, // 是否缓存
	// isAffix: false, // 是否固定+
	// isIframe: false, // 是否内嵌，开启条件，`1、isIframe:true 2、isLink：链接地址不为空`
	// roles: '', // 权限标识，取角色管理
	// btnPower: '', // 菜单类型为按钮时，权限标识
});
// 取消
const onCancel = () => {
	closeDialog();
};

// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (state.dialog.type == 4 || state.dialog.type == 5) {
		const params = {
			name: state.btnName,
			code: state.btnCode,
			parentId: state.dialog.row.id,
			moduleType: 2,
		};
		if (!params.name) return ElMessage.error('请输入按钮名称');
		if (!params.code) return ElMessage.error('请输入按钮唯一标识');
		if (state.dialog.type == 4) {
			await CreateButton(params);
		} else {
			params.parentId = state.dialog.row.parentId;
			await UpdateButton(params, state.dialog.row.id);
		}
		ElMessage.success(state.dialog.type == 4 ? '新增成功' : '修改成功');
		onCancel();
		emit('refresh');
	} else {
		if (!formEl) return;
		const valid = await formEl.validate();
		if (valid) {
			const params = { ...state.ruleForm };
			if (state.dialog.type == 1 || state.dialog.type == 2) {
				if (state.dialog.type == 2) params.parentId = state.dialog.row.id;
				await MenuCreateMenu(params);
			} else {
				if (state.dialog.type == 3) params.parentId = state.dialog.row.parentId;
				await MenuUpdate(params, state.dialog.row.id);
			}
			ElMessage.success(state.dialog.type == 2 ? '修改成功' : '新增成功');
			onCancel();
			emit('refresh');
		}
	}
};
// 页面加载时
onMounted(() => {
	state.menuData = getMenuData(routesList.value);
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
